/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cheetah.youbet.download;

import java.io.IOException;
import org.cheetah.youbet.json.JsonPalinsesto;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author edoardo
 */
public class SisalDownload {

    private static final String LOAD_MENU = "http://www.sisal.it/PalinsestoNuovo/pubblico/menu/sport.jsp?sezione=sport&filtro=tutti";

    public static void main(String[] args) throws IOException {
        SisalDownload s = new SisalDownload();
        s.parseMenu(s.loadMenu());
    }

    public Document loadMenu() throws IOException {
        Document doc = Jsoup.connect(LOAD_MENU).post();
        return doc;
    }

    public void parseMenu(Document doc) throws IOException {
        ObjectMapper om = new ObjectMapper();
        om.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        om.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        Element el = doc.getElementById("menu_sezione_sport_voce_1");

        Elements elements = el.getAllElements();
        for (int i = 0; i < elements.size(); i++) {
            Element e = elements.get(i);
            String onclick = e.attr("onclick");
            if (onclick.indexOf("{") != -1 && onclick.indexOf("}") != -1) {
                String json = onclick.substring(onclick.indexOf("{"), onclick.indexOf("}") + 1);
                JsonPalinsesto jsonPalinsesto = om.readValue(json, JsonPalinsesto.class);
                System.out.println(jsonPalinsesto);
            } else {
                System.out.println("Something wrong... '{' or '}' is missing... Go to next element");
            }

        }

    }

}
